//
//  AreaTableViewController.swift
//  fansarea
//
//  Created by 张 on 2017/12/31.
//  Copyright © 2017年 张. All rights reserved.
//

import UIKit
import CoreData

class AreaTableViewController: UITableViewController ,NSFetchedResultsControllerDelegate,
UISearchResultsUpdating{
    
    
    
//    var ares = ["山西","北京","陕西","湖北","湖南","江西","江苏","山西","北京","陕西","湖北","湖南","江西"]
//
//    var provinces = ["山西","北京","陕西","湖北","湖南","江西","江苏","山西","北京","陕西","湖北","湖南","江西"]
//
//
//    var parts = ["山西","北京","陕西","湖北","湖南","江西","江苏","山西","北京","陕西","湖北","湖南","江西"]
//
//
//    var aresimages = ["xinzhuang","baiyun","chengxi","furong","jinping","nangang","qilihe","shangjie","wuhou","xining","xinzhuang","yaodu","youxi"]
//
//    var visited = [Bool](repeatElement(false, count: 13))
    
    var areas:[AreaMO] = []
    var serarchResults:[AreaMO] = []
    
    var fc : NSFetchedResultsController<AreaMO>!
    var sc :UISearchController?
    
    //搜索匹配逻辑
    func serchFilter(text:String) {
        serarchResults = areas.filter({ (area) -> Bool in
            return (area.name!.localizedStandardContains(text))
        })
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        sc = UISearchController(searchResultsController: nil)
        sc?.searchResultsUpdater = self
        tableView.tableHeaderView = sc?.searchBar
        sc?.dimsBackgroundDuringPresentation = false
        
        sc?.searchBar.searchBarStyle = .minimal // 透明样式
        sc?.searchBar.placeholder = "请输入地区名字检索。。。"
        
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
         self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style:.plain , target: nil, action: nil)
        fetchAllData2()
    }
//    override var preferredStatusBarStyle: UIStatusBarStyle{
//        return .lightContent
//    }
  
    
    //刷新数据
    func updateSearchResults(for searchController: UISearchController) {
        
        if var text = searchController.searchBar.text{
            text = text.trimmingCharacters(in: .whitespaces)
            serchFilter(text: text)
            tableView.reloadData()
        }
    }
    
    
    
    func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        tableView.beginUpdates()
    }
    
    func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        tableView.endUpdates()
    }

    
    func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
        
        switch type {
        case .delete:
            tableView.deleteRows(at: [indexPath!], with: .automatic)
        case.insert :
            tableView.insertRows(at: [newIndexPath!], with: .automatic)
        case.update:
            tableView.reloadRows(at: [indexPath!], with: .automatic)
        default:
            tableView.reloadData()
        }
        if let object = controller.fetchedObjects{
            areas = object as![AreaMO]
        }
        
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view delegate
    
    //定制化右滑菜单
    override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        //分享菜单的实现
        let actionshare = UITableViewRowAction(style: .normal, title: "分享") { (_, indexPath) in
            let actionsheet = UIAlertController(title: "分享", message: nil, preferredStyle: .actionSheet)
            let option1 = UIAlertAction(title: "QQ", style: .default, handler: nil)
            let option2 = UIAlertAction(title: "微信", style: .default, handler: nil)
            let option3 = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            actionsheet.addAction(option1)
            actionsheet.addAction(option2)
            actionsheet.addAction(option3)
            self.present(actionsheet, animated: true, completion: nil)
            
        }
        
        let actiondele = UITableViewRowAction(style:.destructive, title: "删除") { (_, indexPath) in
            
           // self.areas.remove(at: indexPath.row)
            let appdelegate = UIApplication.shared.delegate as! AppDelegate
            let context = appdelegate.persistentContainer.viewContext
            context.delete(self.fc.object(at: indexPath))
            appdelegate.saveContext()
            
            //tableView.deleteRows(at: [indexPath], with: .fade)
        }
        return[actionshare,actiondele]
    }
    /*
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//        print("您点击了",indexPath.section,"组",indexPath.row,"行")
//        let menu = UIAlertController(title: "提示", message: "您点击了第\(indexPath.row)行", preferredStyle: .alert)
//
//        let option1 = UIAlertAction(title: "删除", style: .destructive, handler: nil)
//        let option2 = UIAlertAction(title: "取消", style: .cancel, handler: nil)
//        menu.addAction(option1)
//        menu.addAction(option2)
//        self.present(menu, animated: true, completion: nil)
        
        let menu = UIAlertController(title: "提示", message: "您点击了第\(indexPath.row)行", preferredStyle: .actionSheet)
        
        let option1 = UIAlertAction(title: "删除", style: .destructive, handler: nil)
        let option2 = UIAlertAction(title: "我去过", style: .default) { (_) in
            let cell = tableView.cellForRow(at: indexPath)
            cell?.accessoryType = .checkmark
            self.visited[indexPath.row] = true
        }
        menu.addAction(option1)
        menu.addAction(option2)
        self.present(menu, animated: true, completion: nil)
        //取消选中
        tableView.deselectRow(at: indexPath, animated: true)
        
    }
     */
    
    // MARK: - Table view data source

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        //当搜素条活动时，显示搜素结果
        return sc!.isActive ? serarchResults.count: areas.count
    }

    //设置成自定义的单元格控制器
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)as!CustomTableViewCell
        
        let area = sc!.isActive ? serarchResults[indexPath.row]:areas[indexPath.row]
        
        // Configure the cell...
        cell.nameLable.text = area.name
        cell.thumbImage.image = UIImage(data:area.image!)
        //设置圆角图片
        cell.thumbImage.layer.cornerRadius = cell.thumbImage.frame.size.width/2
        //让上面的设置生效
        cell.thumbImage.clipsToBounds = true
        //修改一炮双响的bug
//        if visited[indexPath.row]{
//            cell.accessoryType = .checkmark
//        }else{
//            cell.accessoryType = .none
//        }
        cell.accessoryType = area.isVistied ? .checkmark:.none
        //设置省
        cell.proviceLable.text = area.province
        //设置区
        cell.partLable.text = area.part
        
        //一炮双响的bug，重复利用的问题
        return cell
    }
 

    //搜索时单元格不可编辑
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return sc!.isActive
    }
    

    
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
           // self.areas.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: .fade)
            //tableView.reloadData() 整体刷新
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
 
    
    

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

   @IBAction func close(segue:UIStoryboardSegue)  {
        
    }
    
    
    
    // MARK: - Navigation
    // 转场前，需要传递值
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
        if segue.identifier == "showAreaDetail"{
            let dest = segue.destination as! DetailTableViewController
            dest.area = sc!.isActive ? serarchResults[tableView.indexPathForSelectedRow!.row]: areas[tableView.indexPathForSelectedRow!.row]
        }
        
    }
    
    //显示数据到界面上
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
       // fetchallData()
        //tableView.reloadData()
        let deafults = UserDefaults.standard
        if  deafults.bool(forKey: "GuiderShow"){
            return
        }
        if let pageVC = storyboard?.instantiateViewController(withIdentifier: "GuideController") as? GuideViewController{
            present(pageVC, animated: true, completion: nil)
        }
        
    }
    
    
    
    //刷新数据
    func fetchAllData2()  {
        let request:NSFetchRequest<AreaMO> = AreaMO.fetchRequest()
        let sd = NSSortDescriptor(key: "name", ascending: true)
        request.sortDescriptors = [sd]
        let appdelegate = UIApplication.shared.delegate as!AppDelegate
        let context = appdelegate.persistentContainer.viewContext
        fc = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
        fc.delegate = self
        do {
            try fc.performFetch()
            if let object = fc.fetchedObjects{
                areas = object
            }
        } catch{
            print(error)
        }
        
    }
//    //从数据库中回去全部数据
//    func fetchallData()  {
//        let appdelegate = UIApplication.shared.delegate as!AppDelegate
//        do {
//          areas = try appdelegate.persistentContainer.viewContext.fetch(AreaMO.fetchRequest())
//        } catch  {
//            print(error)
//        }
//
//    }
    

}
